package com.api.sw.duban.web;

import com.alibaba.fastjson.JSONObject;
import com.api.sw.duban.action.DubanqsAction;
import com.api.sw.duban.action.DubanyTzAction;
import com.api.sw.duban.action.DubanyYbAction;
import com.api.sw.duban.util.CacheUtil;
import com.api.sw.duban.util.DubUtil;
import com.api.sw.duban.util.ExportWord;
import com.api.sw.duban.util.LogTool;
import com.engine.common.util.ParamUtil;
import com.weaver.formmodel.util.FileHelper;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/*

    督办台账

 */
@Path("/dubantz")
public class DbanTzAction {
    private final static LogTool log = new LogTool("/log/duban/",false);
    /*
            督办获取文号
     */
    @GET
    @Path("/getWh")
    @Produces({"text/plain"})
    public String getDbWh(@Context HttpServletRequest var1, @Context HttpServletResponse var2){

        //JSONObject json=new JSONObject();
        JSONObject json=DubUtil.getWh();
        return JSONObject.toJSONString(json);
    }
    /*
        督办任务交办
     */
    @POST
    @Path("/dbanjb")
    @Produces({"text/plain"})
    public String Dbjb(@Context HttpServletRequest var1, @Context HttpServletResponse var2){
        User var4 = HrmUserVarify.getUser(var1, var2);
        String userid="";
        if(var4!=null){
            userid=var4.getUID()+"";
        }

        JSONObject json=new JSONObject();
        JSONObject param=new JSONObject();

        String wrid=var1.getParameter("rwid");//任务ID
        param.put("rwid",wrid);
        param.put("userid",userid);
        //需要启用同步不可 同一个任务多次分解
        try {
            json=(JSONObject) CacheUtil.getInstance().getExecute("DubanAction+"+wrid,"com.api.sw.duban.action.DubanqsAction.Dbjb",param).Execute();
        } catch (Exception e) {
            e.printStackTrace();
            json.put("flag",false);
            json.put("mess","处理异常"+e.getMessage());
        }
        //DubanAction DubanAction=new DubanAction();
        //json=DubanAction.Dbjb(param);
        return JSONObject.toJSONString(json);
    }
    /*
        任务签收
     */
    @GET
    @Path("/dbanqs")
    @Produces({"text/plain"})
    public String  Dbqs(@Context HttpServletRequest var1, @Context HttpServletResponse var2){
        User var4 = HrmUserVarify.getUser(var1, var2);
        String userid="";
        if(var4!=null){
            userid=var4.getUID()+"";
        }
        JSONObject json=new JSONObject();
        String wrid=var1.getParameter("rwid");//任务ID
        String zwrid=var1.getParameter("zwrid");//子任务ID
        String type=var1.getParameter("type");//类型 0：任务接收  1:子任务签收
        JSONObject param=new JSONObject();
        param.put("rwid",wrid);
        param.put("userid",userid);
        param.put("zwrid",zwrid);
        param.put("type",type);
        DubanqsAction DubanqsAction =new DubanqsAction();
        json= DubanqsAction.Dbqs(param);
        return JSONObject.toJSONString(json);
    }
    //获取查询列表数据页面
    @GET
    @Path("/tablelist")
    @Produces({"text/plain"})
    public String getQstablelist(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String, Object> apidatas = new HashMap<String, Object>();
        System.out.println("de");
        try {
            //获取当前用户
            User user = HrmUserVarify.getUser(request, response);
            DubanyTzAction DubantzAction=new DubanyTzAction();
            apidatas.putAll(DubantzAction.getTablelist(ParamUtil.request2Map(request),user));
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }
    //获取查询列表数据页面
    @GET
    @Path("/condition")
    @Produces({"text/plain"})
    public String getQscondition(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String, Object> apidatas = new HashMap<String, Object>();
        System.out.println("de");
        try {
            //获取当前用户
            User user = HrmUserVarify.getUser(request, response);
            DubanyTzAction DubantzAction=new DubanyTzAction();
            apidatas.putAll(DubantzAction.getCondition(ParamUtil.request2Map(request),user));
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }
    //检测是否可以编辑 删除 交办等操作
    @GET
    @Path("/checkButton")
    @Produces({"text/plain"})
    public String checkButton(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String, Object> apidatas = new HashMap<String, Object>();
        JSONObject json=new JSONObject();
        System.out.println("de");
        try {
            //获取当前用户
            User user = HrmUserVarify.getUser(request, response);
            DubanqsAction DubanqsAction =new DubanqsAction();
            json=DubanqsAction.checkButton(ParamUtil.request2Map(request),user);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(json);
    }
    //获取收发文部门对应的督查人员
    @GET
    @Path("/getDcryByReceiveunit")
    @Produces({"text/plain"})
    public String getDcryByReceiveunit(@Context HttpServletRequest request, @Context HttpServletResponse response){
        JSONObject json=new JSONObject();
        String Receiveunit=Util.null2String(request.getParameter("Receiveunitid"));
        String receiveunitry= Util.null2String(DubUtil.getDcryByReceiveunit(Receiveunit));
        json.put("receiveunitry",DubUtil.getHrmspecialobj(receiveunitry));
        return JSONObject.toJSONString(json);
    }
    /*
        导出word
     */
    @GET
    @Path("/daochuwd")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public void loadwd(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
        JSONObject json=new JSONObject();
        //获取sql
        String agent = request.getHeader("user-agent");
        if(agent.contains("Firefox") && !agent.contains("Edge")){
            response.setHeader("content-disposition", "attachment; filename=\"" +  new String("督查台账.doc".replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", "").getBytes("UTF-8"),"ISO-8859-1"));
        }else{
            response.setHeader("content-disposition", "attachment; filename=\"" + URLEncoder.encode("督查台账.doc".replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\"");
        }
        //FileHelper FileHelper=new FileHelper();
//        String typec=FileHelper.getMimeType("督查台账.doc");
//        response.setContentType(typec);
        //FileHelper
        //response.setContentType("application/octet-stream;charset=ISO-8859-1");
//        response.setContentType("application/x-download;charset=ISO-8859-1");
        //response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("督查台账".replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")").replaceAll("%7B", "{").replaceAll("%7D", "}").replaceAll("%5B", "[").replaceAll("%5D", "]").replaceAll("%40", "@").replaceAll("%23", "#").replaceAll("%25", "%").replaceAll("%26", "&").replaceAll("%2B", "+").replaceAll("%27", "'").replaceAll("%20", " "));
        User user = HrmUserVarify.getUser(request, response);
        DubanyTzAction DubantzAction=new DubanyTzAction();
        String sql=DubantzAction.getTablelistSql(ParamUtil.request2Map(request),user);
        log.writeLog("daochuwdsq1--->"+sql);
        Map<String, Object> datamap=DubantzAction.getWordLsit(sql,DubanyTzAction.pageID,user.getUID()+"");
        int row=Util.getIntValue((Integer) datamap.get("row")+"",1) ;
        int col=Util.getIntValue((Integer)datamap.get("col")+"",1) ;
        ExportWord ew = new ExportWord();
        XWPFDocument document = ew.createXWPFDocument(row,col);
        ServletOutputStream resp= response.getOutputStream();
        //ew.exportCheckWordOut(datamap, document,resp);
        //resp.close();
        //document.write(resp)
        //ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray());
        ew.exportCheckWordOut(datamap, document, response.getOutputStream());
    }
    @GET
    @Path("/exportExcel")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public void exportExcel(@Context HttpServletRequest request, @Context HttpServletResponse response){
        response.setContentType("application/x-www-form-urlencoded;charset=utf-8");
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try{
            User user = HrmUserVarify.getUser(request,response);
            new BaseBean().writeLog("###infoWordOut###       apidatas:  "+apidatas.toString());
            String filename ="常规督查台账.doc";
            DubanyTzAction DubantzAction=new DubanyTzAction();
            String sql=DubantzAction.getTablelistSql(ParamUtil.request2Map(request),user);
            log.writeLog("daochuwdsq1--->"+sql);
            Map<String, Object> datamap=DubantzAction.getWordLsit(sql,DubanyTzAction.pageID,user.getUID()+"");
            int row=Util.getIntValue((Integer) datamap.get("row")+"",1) ;
            int col=Util.getIntValue((Integer)datamap.get("col")+"",1) ;
            ExportWord ew = new ExportWord();
            XWPFDocument document = ew.createXWPFDocument(row,col);
            ServletOutputStream resp= response.getOutputStream();
            ew.exportCheckWordOut1(datamap, document);
            log.writeLog("daochuwdsq1--->"+datamap.toString());
            //ew.SreamConvenout(resp);
            String agent = request.getHeader("user-agent");
            if(agent.contains("Firefox")||agent.contains(" Chrome")||agent.contains("Safari")){
                if(agent.contains("Safari")){
                    filename = URLDecoder.decode(filename, "UTF-8");
                }
                filename = new String(filename.getBytes("UTF-8"),"ISO-8859-1");
            }
            filename = handleSlash(filename);
            filename = filename.replace("%2F","");
            filename = filename.replaceAll("\\+", "%20");//空格编码的时候会变成+号
            response.setHeader("content-disposition","attachment; filename=\""+filename +"\"");

            ServletOutputStream out=response.getOutputStream();
            String contentType = FileHelper.getMimeType(filename);
            response.setContentType(contentType);
            document.write(out);
            //document.write(out);
            out.flush();
            out.close();
            //document.close();
            log.writeLog("下载成功!");
        }catch(Exception e){
            e.printStackTrace();
        }

    }
    private String handleSlash(String str){
        return str.replaceAll("/","");
    }

}
